package cn.cf.kxx;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.cf.kxx.adapter.GridGroupAdapter;
import cn.cf.kxx.adapter.GridGroupValveAdapter;
import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.fram.OnActivityInteractionListener;
import cn.cf.kxx.fram.OnFragmentInteractionListener;
import cn.cf.kxx.model.Group;
import cn.cf.kxx.model.dev.Hold;
import cn.cf.kxx.model.Valve;
import cn.cf.kxx.service.IMyAidlCallBack;
import cn.cf.kxx.service.ISerialAidlInterface;
import cn.cf.kxx.tools.Tools;

public class IrrigateActivity extends Fragment implements View.OnClickListener, OnFragmentInteractionListener, AdapterView.OnItemClickListener {

    @Override
    public void onRefrashValues(Object obj) {

    }
    @Override
    public void onRefrashString(String type) {
    }

    @Override
    public void onRefrashValve(int status) {

    }
    GridView gridView,valve_list;

    Button goHome;
    GridGroupAdapter gridGroupAdapter;

    GridGroupValveAdapter gridViewAdapter;

    DataSharedPreferences sharedPreferences;
    List<Group> groups = new ArrayList<>();

    List<Valve> valves = new ArrayList<>();

    View contentView;

    public static IrrigateActivity newInstance(Bundle args) {
        IrrigateActivity fragment = new IrrigateActivity();
        fragment.setArguments(args);
        return fragment;
    }

    String devBh;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = DataSharedPreferences.getInstance();
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            devBh = bundle.getString("devBh");
        }
    }

    //灌溉时间
    EditText runTime,manure,wash;

    Button save;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null){
            contentView = inflater.inflate(R.layout.activity_irrigate,container,false);
            initView();
        }else{
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        }
        return contentView;
    }


    private void initView() {
        save = contentView.findViewById(R.id.save);
        save.setOnClickListener(this);
        runTime = contentView.findViewById(R.id.runTime);
        manure = contentView.findViewById(R.id.manure);
        wash = contentView.findViewById(R.id.wash);
        gridView = contentView.findViewById(R.id.groups);
        valve_list = contentView.findViewById(R.id.valve_list);
        goHome = contentView.findViewById(R.id.goHome);
        goHome.setOnClickListener(this);
        //缓存读出来
        String content = sharedPreferences.getGroup(getActivity());
        Type listType = new TypeToken<ArrayList<Group>>() {}.getType();
        groups = Tools.gson.fromJson(content, listType);
        if(groups.size() == 0){
            Group group;
            for(int i = 1;i < 51;i++){
                group = new Group();
//                group.setParentId(device.getParentId());
                group.setDevBh(devBh);
                group.setZbh((short) i);
                group.setName("默认" + i);
                group.setRemarks("无");
                group.setStatus(0);
                group.setContent("");
                group.setCreateDate(new Date());
                groups.add(group);
            }
            sharedPreferences.addGroup(getActivity(), Tools.gson.toJson(groups));
        }
        gridGroupAdapter = new GridGroupAdapter(getActivity(),groups);
        gridView.setAdapter(gridGroupAdapter);
        gridView.setOnItemClickListener(this);

        //缓存读出来
        content = sharedPreferences.getGuide(getActivity());
        listType = new TypeToken<ArrayList<Valve>>() {}.getType();
        valves = Tools.gson.fromJson(content, listType);
        if(valves.size() == 0){
            Valve valve;
            for(int i = 1;i < 65;i++){
                valve = new Valve();
                valve.setType(1);//无线网关
//                valDevice.setParentId(device.getParentId());
                valve.setDevBh(devBh);
//                valve.setCreateDate(new Date());
                valve.setFmBh(i);
                valve.setLatitude("0.0");
                valve.setLongitude("0.0");
                valve.setVoltage(0f);
                valve.setPulseA(0);
                valve.setPulseB(0);
//                valve.setModifyDate(new Date());
                valve.setName(String.valueOf(i));
                valve.setValveA("0");
                valve.setValveB("0");
                valve.setStatus(0);
                valve.setExtVoltage1(0f);
                valve.setExtVoltage2(0f);
                valve.setHumidity(0f);
                valve.setTemper(0f);
                valves.add(valve);
            }
            sharedPreferences.addGuide(getActivity(),Tools.gson.toJson(valves));
        }
        gridViewAdapter = new GridGroupValveAdapter(getActivity(),new ArrayList<>());
        valve_list.setAdapter(gridViewAdapter);
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    OnActivityInteractionListener onActivityInteractionListener;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onActivityInteractionListener = (OnActivityInteractionListener) context;
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.goHome){
            onActivityInteractionListener.bakeFragment();
        }else if(v.getId() == R.id.save){
            Group group = (Group) gridGroupAdapter.getItem(this.index);

            StringBuilder sb = new StringBuilder();
            Set<Map.Entry<Integer,Valve>> set = gridViewAdapter.getSelectMap().entrySet();
            for(Map.Entry<Integer,Valve> entry : set){
                if(!TextUtils.isEmpty(entry.getValue().getSelect())){
                    sb.append(entry.getKey()+"-A,");
                }
                if(!TextUtils.isEmpty(entry.getValue().getSelect1())){
                    sb.append(entry.getKey()+"-B,");
                }
            }
            String msg = sb.substring(0,sb.toString().length()-1);
            group.setContent(msg);

            String runTimes = runTime.getText().toString().trim();
            group.setRunTime(Integer.parseInt(runTimes));
            String manures = manure.getText().toString().trim();
            group.setManure(Integer.parseInt(manures));
            String washs = wash.getText().toString().trim();
            group.setWash(Integer.parseInt(washs));

            //刷新缓存
            sharedPreferences.addGroup(getActivity(), Tools.gson.toJson(groups));
            Toast.makeText(getActivity(),group.getName() + "保存成功",Toast.LENGTH_LONG).show();
        }
    }

    int index = 0;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //清除原来的选择
        Group hisGroup = (Group) gridGroupAdapter.getItem(this.index);
        hisGroup.setSelect(null);
        gridViewAdapter.getSelectMap().clear();
        //缓存本次选中
        this.index = position;
        //设定选择
        Group group = (Group) gridGroupAdapter.getItem(position);
        group.setSelect("select");
        gridGroupAdapter.notifyDataSetChanged();

        //刷新右侧UI
        List<Valve> content = Tools.gson.fromJson(sharedPreferences.getGuide(getActivity()), new TypeToken<ArrayList<Valve>>() {}.getType());

        if(group.getContent().contains("-")){
            String[] values = group.getContent().split(",");

            String[] ids;
            int index;
            for(int i = 0;i < values.length; i++){
                ids = values[i].split("-");
                index = Integer.parseInt(ids[0]) - 1;
                if(ids[1].equals("A")){
                    content.get(index).setSelect("select");
                }else if(ids[1].equals("B")){
                    content.get(index).setSelect1("select");
                }
            }
        }

        gridViewAdapter.setmDataList(content);
        gridViewAdapter.notifyDataSetChanged();

        runTime.setText(String.valueOf(group.getRunTime()));
        manure.setText(String.valueOf(group.getManure()));
        wash.setText(String.valueOf(group.getWash()));
    }
}
